const Mock = require("mockjs");
const data = { items: [] };
for (let i = 0; i < 3; i++) {
  data.items.push({
    id: Mock.Random.increment(),
    goods_name: "商品" + i,
    thumb: "http://www.jizhang.test/img/黑啤.jpg",
    price: Mock.Random.float(0, 200, 0.01).toFixed(2),
    count: Mock.Random.natural(1, 10)
  });
}
export default {
  fetchList: () => {
    return {
      code: 1,
      msg: "",
      data
    };
  },
  createItem: () => {
    let lastIndex;
    let newId = 1;
    if (data.items.length > 0) {
      lastIndex = data.items.length - 1;
      newId = data.items[lastIndex].id + 1;
    } else {
      lastIndex = 0;
    }
    data.items.push({
      id: newId,
      goods_name: "商品" + newId,
      thumb: "http://www.jizhang.test/img/黑啤.jpg",
      price: Mock.Random.float(0, 200, 0.01).toFixed(2),
      count: Mock.Random.natural(1, 10)
    });
    return {
      code: 1,
      msg: "添加成功",
      data: []
    };
  },
  updateCount: res => {
    const body = JSON.parse(res.body);
    let id = res.url.split("/")[3] || null;
    let count = body.count || 0;
    if (!id || count <= 0) {
      return {
        code: -1,
        msg: "非法参数",
        data: []
      };
    }
    let index;
    id = id * 1;
    data.items.forEach((item, key) => {
      if (item.id * 1 === id) {
        index = key;
      }
    });
    data.items[index].count = count;
    return {
      code: 1,
      msg: "",
      data: []
    };
  },
  deleteItem: res => {
    let id = res.url.split("/")[3] || null;
    if (!id) {
      return {
        code: -1,
        msg: "非法参数",
        data: []
      };
    }
    id = id * 1;
    let index;
    data.items.forEach((item, key) => {
      if (item.id * 1 === id) {
        index = key;
      }
    });
    data.items.splice(index, 1);
    return {
      code: 1,
      msg: "删除成功",
      data: []
    };
  }
};
